package com.elvt.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.elvt.server.pojo.*;
import com.elvt.server.service.*;
import com.elvt.server.utils.RespPageUtil;
import com.elvt.server.utils.RespSult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 *  员工
 * </p>
 *
 * @author 作者：elvt
 * @since 2022-05-21
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @ApiOperation(value = "获取所有员工（分页）")
    @GetMapping
    public RespPageUtil getEmployee(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size , Employee employee, LocalDate[] beginDataSource){
        return employeeService.getEmployeeByPage(currentPage,size,employee,beginDataSource);
    }
    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> findAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJobLevels(){
    return joblevelService.list();
    }
    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> findNation(){
        return nationService.list();
    }
    @ApiOperation(value = "获取所有的职位")
    @GetMapping("/positions")
    public List<Position> findPosition(){
        return positionService.list();
    }
    @ApiOperation(value = "获取所有的部门")
    @GetMapping("/deps")
    public List<Department> findDeps(){
        return departmentService.list();
    }
    @ApiOperation(value = "获取最大工号")
    @GetMapping("/maxWorkID")
    public RespSult maxWorkID(){
        return  employeeService.maxWorkID();
    }
    @ApiOperation(value = "添加员工")
    @PostMapping
    public RespSult addEmp(@RequestBody Employee employee){
        return employeeService.addEmp(employee);
    }
    @ApiOperation(value = "更新员工")
    @PutMapping
    public RespSult updateEmp(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return RespSult.success("更新成功！");
        }
        return RespSult.error("更新失败!");
    }
    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespSult deleteEmpById(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespSult.success("删除成功！");
        }
        return RespSult.error("删除失败！");
    }
    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")

    public void exportEmp(HttpServletResponse response){
        List<Employee> list = employeeService.getAllEmployeeORGgetById(null);
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out=null;
        try {
            //用流的形式传出
            response.setHeader("content-type","application/octet-stream");
            //防止乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation("导入员工数据")
    @PostMapping(value = "/import")
    public RespSult importEmployee(@RequestPart("file") MultipartFile file) {
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            employeeList.forEach(e -> {
                Integer nationId = nationList.get(nationList.indexOf(new Nation(e.getNation().getName()))).getId();
                e.setNationId(nationId);
                Integer politicsStatusId = politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(e.getPoliticsStatus().getName()))).getId();
                e.setPoliticId(politicsStatusId);
                Integer departmentId = departmentList.get(departmentList.indexOf(new Department(e.getDepartment().getName()))).getId();
                e.setDepartmentId(departmentId);
                Integer jobLevelId = joblevelList.get(joblevelList.indexOf(new Joblevel(e.getJoblevel().getName()))).getId();
                e.setJobLevelId(jobLevelId);
                Integer positionId = positionList.get(positionList.indexOf(new Position(e.getPosition().getName()))).getId();
                e.setPosId(positionId);
            });
            if (employeeService.saveBatch(employeeList)) {
                return RespSult.success("成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespSult.error("失败失败");
    }
}
